const app = getApp()
import { requestApi } from '../../api'
import { formatImage } from '../../utils/formatImage';
import { dateFormat } from '../../utils/dateFormat';
import { logUpload } from '../../utils/logUpload';

Page({
    data: {
        winWidth: wx.getSystemInfoSync().windowWidth,
        winHeight: wx.getSystemInfoSync().windowHeight,
        ratio: 3.64 / 3,
        channel: '',
        count: 50,
        banner: [], //轮播图
        currentIdx: 0, // 当前轮播图索引值
        idx: 1,
        security: null, // 品质保障
        kingArea: [], // 金刚区
        type: ['goodsSetCollection', 'goodsIndexPage', 'goodsTopicWeb', 'topGoodsDetail', 'shoppingHelp', 'goodsSpike'],
        recom: null, // 甄选推荐
        featured: '', // 编辑精选
        indexFeed: [], // 首页feed流数据
        isLoading: false, // 加载中
        isMoreEnd: false, // 加载更多
        entrenceTime: '',
        top: app.data.top,
        height: app.data.height,
        isRefresher: false, // 是否下拉刷新
        navBgColor: '',
        navClass: '',
        uploadParam: null,
        scrollTop: 0,
        isShowBackTop: false,
        EditorPicks: '',
        activity_info_pop: null,
        scrollTimer: null
    },
    onShow() {
        app.getRemoteConfigData();
    },
    onLoad(options) {
        let channel = options && options.channel || 'wx_xcx'
        this.init();
        this.data.channel = channel;
        this.data.entrenceTime = dateFormat('yyyy-MM-dd hh:mm:ss:S')

        // 埋点上报
        let uploadParam = {
            cur_page_id: 'OFHomeViewController',
            cur_page_entrance_time: dateFormat('yyyy-MM-dd hh:mm:ss:S')
        }

        logUpload.handleUpload(uploadParam);
    },
    init() {
        this.getIndexData();
        this.getIndexFeed(0);

        if (app.data.configData) {
            if (app.data.configData.activity_info && app.data.configData.activity_info.image) {
                const img_info = app.data.configData.activity_info.image;

                img_info['full_path'] = formatImage.cdnImage(img_info.path, formatImage.THUMBNAIL_M);
                img_info['protocol'] = app.data.configData.activity_info.protocol;

                this.setData({
                    activity_info_pop: img_info
                })
            }
        } else {
            app.configDataCallback = (d) => {
                if (d.activity_info && d.activity_info.image) {
                    const img_info = d.activity_info.image;

                    img_info['full_path'] = formatImage.cdnImage(img_info.path, formatImage.THUMBNAIL_M);
                    img_info['protocol'] = d.activity_info.protocol;

                    this.setData({
                        activity_info_pop: img_info
                    })
                } else {
                    this.setData({
                        activity_info_pop: null
                    })
                }
            }
        }
    },
    getIndexData() {
        const { channel } = this.data;

        app.request({
            url: requestApi.homepage,
            login: false,
            data: {
                is_new_ver: true,
                channel: channel
            },
        }, (data) => {
            if (data.original.data) {
                const item_list = data.original.data.item_list;
                let banner_list = [], security_info = {}, king_area = [], recom_info = {}, recom_list = [], featured_title = '';

                item_list.forEach(item => {
                    // 轮播图
                    if (item.type == 67) {
                        banner_list = item.data.ad_list.map(i => {
                            i.banner_image['path_full'] = formatImage.cdnImage(i.banner_image.path, formatImage.THUMBNAIL_M);
                            i.classify = this.kingAreaType(i.protocol || i.resource_id)
                            return i;
                        });
                    }
                    // 品质保障
                    if (item.type == 102) {
                        security_info = {
                            url: item.data.protocol,
                            path_full: formatImage.cdnImage(item.data.image.path, formatImage.THUMBNAIL_M)
                        }
                    }

                    // 金刚区
                    if (item.type == 108) {
                        item.data.item_list.forEach(i => {
                            i.cover_image['path_full'] = formatImage.cdnImage(i.cover_image.path, formatImage.THUMBNAIL_M);
                            king_area.push({
                                title: i.title,
                                cover_image: i.cover_image,
                                type: this.kingAreaType(i.protocol || i.resource_id),
                                id: i.resource_id
                            })
                        })
                    }

                    // 甄选推荐
                    if (item.type == 113) {
                        recom_info = item.data;
                    }
                    if (item.type == 100) {
                        item.data.list[0].data.list.forEach(i => i.cover_image['path_full'] = formatImage.cdnImage(i.cover_image.path, formatImage.THUMBNAIL_M));
                        recom_list.push({
                            type: item.data.list[0].type,
                            child: item.data.list[0].data.list
                        })
                    }

                    if (item.type == 116) {
                        featured_title = item.name;
                    }
                });
                recom_info['list'] = recom_list;

                this.setData({
                    banner: banner_list,
                    security: security_info,
                    kingArea: king_area,
                    recom: recom_info,
                    currentIdx: 0,
                    featured: featured_title
                })
            }
        }, (error) => {
            wx.showModal({
                title: '提示',
                showCancel: false,
                content: error,
            })
        }, () => {
            this.setData({
                isRefresher: false
            }) 
        });
    },
    getIndexFeed(start) {
        const { channel, count, indexFeed, isMoreEnd } = this.data;
        this.setData({
            isLoading: true
        });
        app.request({
            url: requestApi.indexFeed,
            login: false,
            data: {
                start,
                count,
                is_new_ver: true,
                channel: channel
            },
        }, (data) => {
            if (data.original.ret_code == 200) {
                let arr = [], upParams = {};

                data.original.data.item_list.forEach(item => {
                    if (item.type == 34) {
                        arr.push(item.data);
                    }
                })

                if (start > 0) {
                    arr = [].concat(indexFeed, arr);
                }

                if (indexFeed.length >= data.original.data.total) {
                    isMoreEnd = !isMoreEnd
                }

                upParams = {
                    channel,
                    ref_page_id: 'OFHomeViewController',
                    ref_opt_protocol: '/pages/index/index',
                    opt_resource_type: 5,
                    opt_resource_area: 119,
                    opt_protocol: '/pages/goods/goodsDetail/goodsDetail',
                }

                this.setData({
                    indexFeed: arr,
                    isMoreEnd,
                    uploadParam: upParams
                })
            }
        }, (error) => {
            // wx.showModal({
            //     title: '提示',
            //     showCancel: false,
            //     content: error,
            // })
            this.setData({
                isMoreEnd: true
            });
        }, () => {
            this.setData({
                isLoading: false
            });
        });
    },
    swiperChange(e) {
        const { current, source } = e.detail;

        this.setData({
            idx: current + 1
        })
    },
    goBanner(e) {
        const { banner, channel, entrenceTime } =  this.data;
        const index = e.currentTarget.id;
        const info = banner[index];
        let tid = info.tid;
        let opt_resource_id = info.tid;
        let opt_time = dateFormat('yyyy-MM-dd hh:mm:ss:S');
        let opt_resource_type = 1;
        let ref_opt_resource_type = 6;  // 轮播图
        let opt_protocol = '';
        let url = '';

        switch(info.resource_type) {
            case 1: // 专题
                opt_protocol = '/pages/topic/topicDetail/topicDetail'

                url = opt_protocol + '?tid=' + tid;
                break;
            case 2: // 合集
                opt_resource_type = 2;
                opt_protocol = '/pages/activity/activityDetail/activityDetail';
                
                url = opt_protocol + '?tId=' + tid;
                break;
            case 4: // 商品
                opt_resource_type = 5;
                opt_protocol = '/pages/goods/goodsDetail/goodsDetail';

                url =  opt_protocol + '?gid=' + tid;
            break;
            case 6: // 外链
                url = decodeURIComponent(info.protocol).split('urlString=')[1];
                break;
            case 12: // 索引page页
                opt_resource_type = 99;
                opt_protocol = '/pages/categoryHall/categoryHall';

                url =  opt_protocol + '?isKing=true&tid=' + tid;
            break;
            case 13: // 秒杀专场
                opt_resource_type = 2;
                opt_protocol = '/pages/webView/webView';

                url = 'channel=' + channel + '&ref_page_id=OFHomeViewController' + '&ref_opt_resource_type=' + ref_opt_resource_type + '&ref_opt_protocol=pages/index/index&opt_resource_id=' + opt_resource_id + '&opt_resource_type=' + opt_resource_type + '&opt_protocol=' + opt_protocol + '&opt_time=' + opt_time + '&log_type=1&ref_write_sever_timestamp=' + entrenceTime + '&opt_resource_area_index=' + index;
            break;
            default:
        }

        if (info.resource_type == 6) {
            wx.navigateTo({
                url: `/pages/webView/webView?url=${url}`,
            })
        } else if (info.resource_type == 13) {
            url = encodeURIComponent(url)
            wx.navigateTo({
                url: `/pages/webView/webView?urlParams=${url}&type=flashsale&tid=${tid}`,
            })
        } else {
            wx.navigateTo({
                url: url + '&channel=' + channel + '&ref_page_id=OFHomeViewController' + '&ref_opt_resource_type=' + ref_opt_resource_type + '&ref_opt_protocol=pages/index/index&opt_resource_id=' + opt_resource_id + '&opt_resource_type=' + opt_resource_type + '&opt_protocol=' + opt_protocol + '&opt_time=' + opt_time + '&log_type=1&ref_write_sever_timestamp=' + entrenceTime + '&opt_resource_area_index=' + index
            });
        }
    },
    // 提取金刚区链接类别
    kingAreaType(protocol) {
        const { type } = this.data;

        return type.find(i => protocol.indexOf(i) >= 0);
    },
    // 正品保障
    goService() {
        const { security } = this.data;
        let url = '';

        if (security.url) {
            url = decodeURIComponent(security.url).split('urlString=')[1];
            wx.navigateTo({
                url: `/pages/webView/webView?url=${url}&type=service`,
            })
        }
    },
    // 金刚区入口
    goKingarea(e) {
        const { index } = e.currentTarget.dataset;
        const { kingArea, channel, entrenceTime } = this.data;
        const info = kingArea[index];
        let tid = info.id;
        let opt_resource_id = info.id;
        let opt_time = dateFormat('yyyy-MM-dd hh:mm:ss:S');
        let opt_resource_type = 1;
        let ref_opt_resource_type = 95;
        let opt_protocol = '';
        let url = '';

        switch(info.type) {
            case 'goodsTopicWeb': // 专题
                opt_resource_type = 1;
                opt_protocol = '/pages/topic/topicDetail/topicDetail'

                url = opt_protocol + '?tid=' + tid;
                break;
            case 'goodsSetCollection': // 合集
                opt_resource_type = 2;
                opt_protocol = '/pages/activity/activityDetail/activityDetail';
                
                url = opt_protocol + '?tId=' + tid;
                break;
            case 'topGoodsDetail': // 商品
                opt_resource_type = 5;
                opt_protocol = '/pages/goods/goodsDetail/goodsDetail';

                url =  opt_protocol + '?gid=' + tid;
            break;
            case 'shoppingHelp': // 外链
                url = decodeURIComponent(tid).split('urlString=')[1];
                break;
            case 'goodsIndexPage': // 索引page页
                opt_resource_type = 99;
                opt_protocol = '/pages/categoryHall/categoryHall';

                url =  opt_protocol + '?isKing=true&tid=' + tid;
            break;
            case 'goodsSpike': // 秒杀合集
                opt_resource_type = 2;
                opt_protocol = '/pages/webView/webView';

                url = 'channel=' + channel + '&ref_page_id=OFHomeViewController' + '&ref_opt_resource_type=' + ref_opt_resource_type + '&ref_opt_protocol=pages/index/index&opt_resource_id=' + opt_resource_id + '&opt_resource_type=' + opt_resource_type + '&opt_protocol=' + opt_protocol + '&opt_time=' + opt_time + '&log_type=1&ref_write_sever_timestamp=' + entrenceTime + '&opt_resource_area_index=' + index;
            break;
            default:
        }

        if (info.type == 'shoppingHelp') {
            wx.navigateTo({
                url: `/pages/webView/webView?url=${url}`,
            })
            
        } else if (info.type == 'goodsSpike') {
            url = encodeURIComponent(url)
            wx.navigateTo({
                url: `/pages/webView/webView?urlParams=${url}&type=flashsale&tid=${tid}`,
            })
        } else {
            wx.navigateTo({
                url: url + '&channel=' + channel + '&ref_page_id=OFHomeViewController' + '&ref_opt_resource_type=' + ref_opt_resource_type + '&ref_opt_protocol=pages/index/index&opt_resource_id=' + opt_resource_id + '&opt_resource_type=' + opt_resource_type + '&opt_protocol=' + opt_protocol + '&opt_time=' + opt_time + '&log_type=1&ref_write_sever_timestamp=' + entrenceTime + '&opt_resource_area_index=' + index
            });
        }
    },
    goRecom(e) {
        const { info, index } = e.currentTarget.dataset;
        console.log(info)
        const { channel, entrenceTime } =  this.data;
        let tid = info.resource_id;
        let opt_resource_id = info.resource_id;
        let opt_time = dateFormat('yyyy-MM-dd hh:mm:ss:S');
        let opt_resource_type = 1;
        let ref_opt_resource_type = 41;
        let opt_protocol = '';
        let url = '';

        switch(info.resource_type) {
            case 1: // 专题
                opt_protocol = '/pages/topic/topicDetail/topicDetail'

                url = opt_protocol + '?tid=' + tid;
                break;
            case 2: // 合集
                opt_resource_type = 2;
                opt_protocol = '/pages/activity/activityDetail/activityDetail';
                
                url = opt_protocol + '?tId=' + tid;
                break;
            case 4: // 商品
                opt_resource_type = 5;
                opt_protocol = '/pages/goods/goodsDetail/goodsDetail';

                url =  opt_protocol + '?gid=' + tid;
            break;
            case 6: // 外链
                break;
            case 12: // 索引page页
                opt_resource_type = 99;
                opt_protocol = '/pages/categoryHall/categoryHall';

                url =  opt_protocol + '?isKing=true&tid=' + tid;
            break;
            case 13: // 秒杀专场
                opt_resource_type = 2;
                opt_protocol = '/pages/webView/webView';

                url = 'channel=' + channel + '&ref_page_id=OFHomeViewController' + '&ref_opt_resource_type=' + ref_opt_resource_type + '&ref_opt_protocol=pages/index/index&opt_resource_id=' + opt_resource_id + '&opt_resource_type=' + opt_resource_type + '&opt_protocol=' + opt_protocol + '&opt_time=' + opt_time + '&log_type=1&ref_write_sever_timestamp=' + entrenceTime + '&opt_resource_area_index=' + index;
            break;
            default:
        }

        if (info.resource_type != 6) {
            if (info.resource_type == 13) {
                url = encodeURIComponent(url)
                wx.navigateTo({
                    url: `/pages/webView/webView?urlParams=${url}&type=flashsale&tid=${tid}`,
                })
            } else {
                wx.navigateTo({
                    url: url + '&channel=' + channel + '&ref_page_id=OFHomeViewController' + '&ref_opt_resource_type=' + ref_opt_resource_type + '&ref_opt_protocol=pages/index/index&opt_resource_id=' + opt_resource_id + '&opt_resource_type=' + opt_resource_type + '&opt_protocol=' + opt_protocol + '&opt_time=' + opt_time + '&log_type=1&ref_write_sever_timestamp=' + entrenceTime + '&opt_resource_area_index=' + index
                });
            }
        } else {
            // 是否是新人专区
            if (info.protocol.indexOf('newCommer') >= 0) {
                url = '/pages/newcomer/newcomer';
            
                wx.navigateTo({
                    url: url + '?channel=' + channel + '&ref_page_id=OFHomeViewController' + '&ref_opt_resource_type=' + ref_opt_resource_type + '&ref_opt_protocol=pages/index/index&opt_resource_id=' + opt_resource_id + '&opt_resource_type=' + opt_resource_type + '&opt_protocol=' + opt_protocol + '&opt_time=' + opt_time + '&log_type=1&ref_write_sever_timestamp=' + entrenceTime + '&opt_resource_area_index=' + index
                });
            }
        }
    },
    goSearch() {
        wx.navigateTo({
          url: '/pages/search/searchResult/searchResult',
        })
    },
    onPullDownRefresh() {
        this.setData({
            isRefresher: true,
            isMoreEnd: false
        }) 
        this.init();
    },
    loadMore() {
        const { indexFeed, isMoreEnd } = this.data;
        
        if (!isMoreEnd) {
            this.getIndexFeed(indexFeed.length);
        }
    },
    onScroll(e) {
        const { scrollTop } = e.detail;
        let { winWidth, winHeight, ratio, activity_info_pop, scrollTimer } = this.data;
        let bg = '', opacity = 0, active = '', showBackTop = false;
        
        opacity = Math.ceil(((scrollTop / (winWidth * ratio)) >= 1 ? 1 : (scrollTop / (winWidth * ratio)) <= .5 ? 0 : (scrollTop / (winWidth * ratio))) * 100);

        if ((scrollTop / (winWidth * ratio)) <= 1) {
            opacity = (opacity / 100).toFixed(1);
        } else {
            opacity = 1;
        }

        if (opacity > .8) {
            active = 'active';
        }

        if (scrollTop >= winHeight) {
            showBackTop = true;
        } else {
            showBackTop = false;
        }

        bg = 'rgba(255, 255, 255, '+ opacity +')';
        if (activity_info_pop) {
            activity_info_pop['isHide'] = true;

            clearTimeout(scrollTimer);
            scrollTimer = setTimeout(() => {
                activity_info_pop['isHide'] = false;
    
                this.setData({
                    activity_info_pop,
                    scrollTimer
                })
            }, 1500);
        }
        this.setData({
            navBgColor: bg,
            navClass: active,
            isShowBackTop: showBackTop,
            activity_info_pop,
            scrollTimer
        })
    },
    goBackTop() {
        this.setData({
            scrollTop: 0
        })
    },
    goActivityPop() {
        const { activity_info_pop } = this.data;
        // mstore:\/\/type@11*collection_id@228261
        // mfashion://cmd@openref*value@https://tm.ofashion.com.cn/hotTopic?tid=25179*forward
        // mstore://type@7*uid@34351047
        // ofashion://native/goodsIndexPage?indexID=116
        
        const { channel, entrenceTime } =  this.data;
        let tid = '';
        let opt_resource_id = '';
        let opt_time = dateFormat('yyyy-MM-dd hh:mm:ss:S');
        let opt_resource_type = 1;
        let ref_opt_resource_type = 41;
        let opt_protocol = '';
        let url = '';
        let isWebView = false;

        if (activity_info_pop.protocol.indexOf('hotTopic') > 0) {
                opt_protocol = '/pages/topic/topicDetail/topicDetail'
                tid = activity_info_pop.protocol.split('tid=')[1].split('*forward')[0];
                opt_resource_id = tid
                url = opt_protocol + '?tid=' + tid;
        } else if (activity_info_pop.protocol.indexOf('collection_id') > 0) {
                opt_resource_type = 2;
                opt_protocol = '/pages/activity/activityDetail/activityDetail';
                tid = activity_info_pop.protocol.split('collection_id@')[1];
                opt_resource_id = tid
                url = opt_protocol + '?tId=' + tid;
        } else if (activity_info_pop.protocol.indexOf('uid') > 0) {
                opt_protocol = '/pages/store/store';
                tid = activity_info_pop.protocol.split('uid@')[1];
                opt_resource_id = tid
                url =  opt_protocol + '?seller_uid=' + tid;
        } else if (activity_info_pop.protocol.indexOf('goodsIndexPage') > 0) {
                opt_resource_type = 99;
                opt_protocol = '/pages/categoryHall/categoryHall';
                tid = activity_info_pop.protocol.split('uid@')[1];
                opt_resource_id = tid
                url =  opt_protocol + '?isKing=true&tid=' + tid;
        } else {
                opt_resource_type = 2;
                opt_protocol = '/pages/webView/webView';

                url = activity_info_pop.protocol;
                isWebView = true;
        }

        wx.navigateTo({
            url: `/pages/newcomer/newcomer`,
        })

        // if (isWebView) {
        //     wx.navigateTo({
        //         url: `/pages/webView/webView?url=${url}`,
        //     })
        // } else {
        //     wx.navigateTo({
        //         url: url + '&channel=' + channel + '&ref_page_id=OFHomeViewController' + '&ref_opt_resource_type=' + ref_opt_resource_type + '&ref_opt_protocol=pages/index/index&opt_resource_id=' + opt_resource_id + '&opt_resource_type=' + opt_resource_type + '&opt_protocol=' + opt_protocol + '&opt_time=' + opt_time + '&log_type=1&ref_write_sever_timestamp=' + entrenceTime + '&opt_resource_area_index=' + index
        //     });
        // }
    },
    onShareAppMessage() {
        return {
            title: '迷橙－值得信赖的全球时尚精品购物网站',
            desc: '轻松海购时尚小众设计师精品，各大时尚奢侈品牌新款、限量款、走秀款,100%正品保证。',
            path: '/pages/index/index?channel=wx_xcx',
            imageUrl: '',
        }
    }
})